﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using SimpleNoteLib.ApiRequests;
using SimpleNoteLib.Extensions;
using SimpleNoteLib.Json;

namespace SimpleNoteLib
{
    public class NotesIndexer
    {
        public ICollection<NoteLite> GetNotesLite(DateTime? since = null)
        {
            List<NoteLite> result = new List<NoteLite>();
            string mark = null;
            IndexJson index = null;
            do
            {
                IndexRequest request = new IndexRequest
                {
                    Mark = index != null ? index.mark : null,
                    Since = since.HasValue ? since.Value.ToUnixTimeString() : null
                };
                string jsonResp = request.SendAndGetResponse();
                index = JsonBase.FromString<IndexJson>(jsonResp);
                index.data.ToList().ForEach(d => result.Add(NoteLite.FromJson(d)));
            }
            while (string.IsNullOrWhiteSpace(index.mark) == false);

            return result;
        }

        public ICollection<Note> GetNotes(DateTime? since = null)
        {
            var notesLite = GetNotesLite(since);
            List<Note> result = new List<Note>();
            foreach (NoteLite noteLite in notesLite)
            {
                GetNoteRequest request = new GetNoteRequest(noteLite.Key);
                string noteJson = request.SendAndGetResponse();
                Note note = Note.FromJson(JsonBase.FromString<NoteJson>(noteJson));
                result.Add(note);
            }
            return result;
        }
    }
}
